﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using FU.SE0208.G1.Controller;

namespace FU.SE0208.G1
{
    public partial class frmOrder : Form
    {
        // Error
        private const string ERR_LOAD_DATA_FAIL = "Fail to load Order! There are some problems with database server";
        private const string ERR_LOAD_CUSTOMER_FAIL = "Fail to load Customer! There are some problems with database server";
        private const string ERR_LOAD_PRO_ID_FAIL = "Fail to load Product ID! There are some problems with database server";
        private const string ERR_DEL_ORDER_FAIL = "Fail to delete Order! There are some problems with database server";
        private const string ERR_WRONG_PRO_ID = "Product ID is wrong!";
        private const string ERR_LOAD_PRO_FAIL = "Fail to load Product! There are some problems with database server";
        private const string ERR_LOAD_SERIAL_FAIL = "Fail to load Serial! There are some problems with database server";
        private const string ERR_PRODUCT_NULL = "There is not any these Products in our storage!";
        private const string ERR_QUANTITY_VALIDATE = "Quantity must be integer, >= 0, <= ";
        private const string ERR_ADD_ORDER_DETAIL_FAIL = "Fail to add new Order Detail! There are some problems with database server";
        private const string ERR_ADD_ORDER_FAIL = "Fail to add new Order! There are some problems with database server";
        private const string ERR_UPDATE_ORDER_DETAIL_FAIL = "Fail to update Order Detail! There are some problems with database server";
        private const string ERR_UPDATE_ORDER_FAIL = "Fail to update Order! There are some problems with database server";
        private const string ERR_UPDATE_SERIAL_FAIL = "Fail to update Serial! There are some problems with database server";
        private const string ERR = "";

        // Message
        private const string SMS_DELETE_ASK = "Do you want to delete the current Order?";
        private const string SMS_SAVE_ASK = "Do you want to save the current Order?";    
        private const string SMS = "";

        // Const
        private const string STR_TABLE_ORDER = "Table_Order";
        private const string STR_TABLE_ORDER_DETAIL = "Table_Order_Detail";
        private const string STR_TABLE_STATUS = "Table_Status";
        private const string STR_TABLE_CUSTOMER = "Table_Customer";
        private const string STR_TABLE_PRO_ID = "Table_ProId";
        private const string STR_AVAILABE_STATUS = "0";
        private const string STR_DISCOUNT_PERCENT = "P";

        private const string STR_TABLE_PRO_BY_ID = "Table_ProId_";
        private const string STR_TABLE_SERIAL_BY_PRO_ID = "Table_Serial_";
        private const string STR_TABLE_ADD_ORDER_DETAIL = "Table_Add_Order_Detail";

        private const string STR_MODE_NORMAL = "Mode_Normal";
        private const string STR_MODE_ADD = "Mode_Add";
        private const string STR_MODE_EDIT = "Mode_Edit";

        private const string STR_COLUMN_DEL = "Del";

        // Const data
        private string[] ARR_STATUS_TEXT = { "Y", "N" };
        private string[] ARR_STATUS_VALUE = { "0", "1" };

        // Main dataset contains order and order_detail
        private DataSet dsData = null;

        // Load control
        private bool bLoaded = false;

        // Global var
        private string sMode = STR_MODE_NORMAL;
        private int iOrder = -1;
        //private int iOrderDetail = -1;

        /*
         * -------------------------------------------------------------------------------
         */

        public frmOrder()
        {
            InitializeComponent();
        }

        // Load order and order detail
        private bool loadOrder()
        {
            OrderHandler handler = new OrderHandler();
            if (handler.getAllOrder(dsData, STR_TABLE_ORDER, STR_TABLE_ORDER_DETAIL) == false)
            {
                return false;
            }

            return true;
        }

        // Display order
        private bool displayOrder()
        {
            dgvOrder.DataSource = dsData;
            dgvOrder.DataMember = STR_TABLE_ORDER;

            for (int i = 0; i < dsData.Tables[STR_TABLE_ORDER].Columns.Count; i++)
            {
                clbShowColumn.Items.Add(dsData.Tables[STR_TABLE_ORDER].Columns[i].ColumnName);
                clbShowColumn.SetItemChecked(i, true);
            }

            return true;
        }


        private bool loadCustomer()
        {
            CustomerHandler handler = new CustomerHandler();
            if (handler.getCustomerList(dsData, STR_TABLE_CUSTOMER) == false)
            {
                return false;
            }

            cbbCustomer.DataSource = dsData.Tables[STR_TABLE_CUSTOMER];
            cbbCustomer.DisplayMember = "Name";
            cbbCustomer.ValueMember = "CusID";

            cbbCustomer.SelectedIndex = -1;

            return true;
        }

        private bool loadProId()
        {
            ProductHandler handler = new ProductHandler();
            if (handler.getProIdList(dsData, STR_TABLE_PRO_ID) == false)
            {
                return false;
            }

            cbbProductID.DataSource = dsData.Tables[STR_TABLE_PRO_ID];
            cbbProductID.DisplayMember = "ProId";
            cbbProductID.ValueMember = "ProId";

            cbbProductID.SelectedIndex = -1;

            return true;
        }

        private bool loadStatus()
        {
            dsData.Tables.Add(STR_TABLE_STATUS);
            DataTable dt = dsData.Tables[STR_TABLE_STATUS];

            dt.Columns.Add("STATUS_TEXT", Type.GetType("System.String"));
            dt.Columns.Add("STATUS_VALUE", Type.GetType("System.String"));

            for (int j = 0; j < ARR_STATUS_TEXT.Length; j++)
            {
                DataRow dr = dt.NewRow();

                dr["STATUS_TEXT"] = ARR_STATUS_TEXT[j];
                dr["STATUS_VALUE"] = ARR_STATUS_VALUE[j];

                dt.Rows.Add(dr);
            }

            cbbStatus.DataSource = dsData.Tables[STR_TABLE_STATUS];
            cbbStatus.DisplayMember = "STATUS_TEXT";
            cbbStatus.ValueMember = "STATUS_VALUE";

            cbbStatus.SelectedIndex = -1;

            return true;
        }

        private void frmOrder_Load(object sender, EventArgs e)
        {
            bLoaded = false;
            dsData = new DataSet();

            // Load data
            if (loadOrder() == false)
            {
                MessageBox.Show(ERR_LOAD_DATA_FAIL);
                return;
            }

            // Display data order
            displayOrder();

            // Load customer combobox
            if (loadCustomer() == false)
            {
                MessageBox.Show(ERR_LOAD_CUSTOMER_FAIL);
                return;
            }

            // Load product ID combobox
            if (loadProId() == false)
            {
                MessageBox.Show(ERR_LOAD_PRO_ID_FAIL);
                return;
            }

            // Load status
            loadStatus();

            // Lock control
            lockControl(true);

            // unLock button add order
            btnAddOrder.Enabled = true;

            // Lock order detail
            lockOrderDetail(true);

            // Hide button
            showButton(false);

            bLoaded = true;
        }

        private void btnCheckAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < clbShowColumn.Items.Count; i++)
            {
                clbShowColumn.SetItemChecked(i, true);
            }
        }

        private void btnUnCheckAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < clbShowColumn.Items.Count; i++)
            {
                clbShowColumn.SetItemChecked(i, false);
            }
        }

        private void clbShowColumn_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (bLoaded == false) return;

            dgvOrder.Columns[clbShowColumn.Items[e.Index].ToString()].Visible = !clbShowColumn.GetItemChecked(e.Index);
        }

        // Lock datagridview order detail columns
        private void lockGridColumn()
        {
            for (int i = 0; i < dgvOrderDetail.Columns.Count; i++)
            {
                dgvOrderDetail.Columns[i].ReadOnly = true;
            }

            // Let useredit only quantity column
            dgvOrderDetail.Columns["Product quantity"].ReadOnly = false;
        }

        private void dgvOrder_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            // Load order detail for datagridview
            DataView dv = new DataView(dsData.Tables[STR_TABLE_ORDER_DETAIL]);
            dv.RowFilter = "[Order ID] = " + dgvOrder["Order ID", e.RowIndex].Value.ToString();
            dgvOrderDetail.DataSource = dv;

            // Hide column orderID
            dgvOrderDetail.Columns["Order ID"].Visible = false;

            // Lock datagridview order detail columns
            lockGridColumn();

            // Display order information
            grbOrderDetail.Text = "OrderID = " + dgvOrder["Order ID", e.RowIndex].Value.ToString();
            dtpOrderDate.Value = Convert.ToDateTime(dgvOrder["Order date", e.RowIndex].Value.ToString());
            dtpDevilDate.Value = Convert.ToDateTime(dgvOrder["Delivery date", e.RowIndex].Value.ToString());
            txtDelivName.Text = dgvOrder["Delivery name", e.RowIndex].Value.ToString();
            txtDelivAdd.Text = dgvOrder["Delivery address", e.RowIndex].Value.ToString();
            txtDelivPhone.Text = dgvOrder["Delivery phone", e.RowIndex].Value.ToString();
            cbbCustomer.Text = dgvOrder["Customer name", e.RowIndex].Value.ToString();
            cbbStatus.SelectedValue = dgvOrder["Status", e.RowIndex].Value.ToString();
            txtNote.Text = dgvOrder["Note", e.RowIndex].Value.ToString();

            // Calculate the sum
            calculateData();

            // Unlock Control
            lockControl(false);

            iOrder = e.RowIndex;
        }

        private void lockControl(bool bLock)
        {
            btnAddOrder.Enabled = !bLock;
            btnEdit.Enabled = !bLock;
            btnDel.Enabled = !bLock;
        }

        private void lockControl1(bool bLock)
        {
            btnAddOrder.Enabled = !bLock;
            //btnEdit.Enabled = !bLock;
            //btnDel.Enabled = !bLock;
        }

        private void lockControl2(bool bLock)
        {
            //btnAddOrder.Enabled = !bLock;
            btnEdit.Enabled = !bLock;
            btnDel.Enabled = !bLock;
        }

        private void lockOrderDetail(bool bLock)
        {
            dgvOrderDetail.ReadOnly = bLock;

            if (!sMode.Equals(STR_MODE_EDIT))
            {
                cbbProductID.Enabled = !bLock;
                btnAddProduct.Enabled = !bLock;
            }

            dtpOrderDate.Enabled = !bLock;
            dtpDevilDate.Enabled = !bLock;
            txtDelivName.ReadOnly = bLock;
            txtDelivAdd.ReadOnly = bLock;
            txtDelivPhone.ReadOnly = bLock;
            cbbCustomer.Enabled = !bLock;
            btnAddCustomer.Enabled = !bLock;
            cbbStatus.Enabled = !bLock;
            txtNote.ReadOnly = bLock;
        }

        private void showButton(bool bShow)
        {
            btnSave.Visible = bShow;
            btnCancel.Visible = bShow;
            dgvOrder.Enabled = !bShow;
        }

        private void clearOrderDetail()
        {
            dgvOrderDetail.DataSource = null;
            cbbProductID.SelectedIndex = -1;
            dtpOrderDate.Value = DateTime.Today;
            dtpDevilDate.Value = DateTime.Today;
            txtDelivName.Text = null;
            txtDelivAdd.Text = null;
            txtDelivPhone.Text = null;
            cbbCustomer.SelectedIndex = -1;
            cbbStatus.SelectedValue = STR_AVAILABE_STATUS;
            txtNote.Text = null;
            txtSum.Text = null;
            txtTax.Text = null;
        }

        private void btnAddOrder_Click(object sender, EventArgs e)
        {
            // Set the mode
            sMode = STR_MODE_ADD;

            showButton(true);
            lockControl(true);
            lockOrderDetail(false);

            // Clean detail
            clearOrderDetail();

            // Show new grbOrderDetail label
            grbOrderDetail.Text = "New order detail";

            // Lock datagridview order detail
            //dgvOrderDetail.ReadOnly = true;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            // Set the mode
            sMode = STR_MODE_EDIT;

            showButton(true);
            lockControl(true);
            lockOrderDetail(false);

            // Lock datagridview order detail columns
            lockGridColumn();
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(SMS_DELETE_ASK, "Delete", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            int OrderId = Convert.ToInt32(dgvOrder["Order ID", iOrder].Value.ToString());

            // Delete in database
            OrderHandler handler = new OrderHandler();
            if (handler.delOrderByID(OrderId) == false)
            {
                MessageBox.Show(ERR_DEL_ORDER_FAIL);
                return;
            }

            if (handler.delOrderDetailByID(OrderId) == false)
            {
                MessageBox.Show(ERR_DEL_ORDER_FAIL);
                return;
            }

            // Delete in datagridview order
            dgvOrder.Rows.RemoveAt(iOrder);

            // Clean datagridview order detail
            dgvOrderDetail.DataSource = null;

            if (dgvOrder.Rows.Count == 0)
            {
                lockControl2(true);
            }
        }

        private void btnAddProduct_Click(object sender, EventArgs e)
        {
            string ProId = cbbProductID.Text;

            if (cbbProductID.SelectedIndex < 0)
            {
                MessageBox.Show(ERR_WRONG_PRO_ID + " " + ProId);
                return;
            }

            ProductHandler handler = new ProductHandler();

            // Get all serial in this product ID
            if (handler.getSerialByProId(dsData, STR_TABLE_SERIAL_BY_PRO_ID + ProId, ProId) == false)
            {
                MessageBox.Show(ERR_LOAD_SERIAL_FAIL);
                return;
            }

            // Check if the product ID don't have any items
            if (dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + ProId].Rows.Count == 0)
            {
                MessageBox.Show(ERR_PRODUCT_NULL);
                // Remove the table in dataset
                dsData.Tables.Remove(STR_TABLE_SERIAL_BY_PRO_ID + ProId);
                return;
            }

            // Get product by ID add to datagridview order detail
            // Create new table in dataset
            if (dsData.Tables.Contains(STR_TABLE_ADD_ORDER_DETAIL) == false)
            {
                dsData.Tables.Add(STR_TABLE_ADD_ORDER_DETAIL);

                // Column Del
                DataGridViewImageColumn cDel = new DataGridViewImageColumn();
                cDel.HeaderText = STR_COLUMN_DEL;
                cDel.Width = 30;
                cDel.Name = STR_COLUMN_DEL;
                cDel.DataPropertyName = STR_COLUMN_DEL;
                dgvOrderDetail.Columns.Add(cDel);

                if (handler.getProductById(dsData, STR_TABLE_ADD_ORDER_DETAIL, ProId) == false)
                {
                    MessageBox.Show(ERR_LOAD_PRO_FAIL);
                    return;
                }
                dsData.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Product quantity"] = 0;

                dgvOrderDetail.DataSource = dsData;
                dgvOrderDetail.DataMember = STR_TABLE_ADD_ORDER_DETAIL;

                // Column Del
                dgvOrderDetail[STR_COLUMN_DEL, 0].Value = Properties.Resources.cancel;
                dgvOrderDetail["Product quantity", 0].ToolTipText = "Max = " + dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + ProId].Rows.Count;

                // lock datagridview order detail
                lockGridColumn();
            }
            else
            {
                //if (!dgvOrderDetail.DataMember.Equals(STR_TABLE_ADD_ORDER_DETAIL))
                //{
                //    dgvOrderDetail.DataSource = dsData;
                //    dgvOrderDetail.DataMember = STR_TABLE_ADD_ORDER_DETAIL;
                //}

                if (dgvOrderDetail.Columns.Contains(STR_COLUMN_DEL) == false)
                {
                    // Column Del
                    DataGridViewImageColumn cDel = new DataGridViewImageColumn();
                    cDel.HeaderText = STR_COLUMN_DEL;
                    cDel.Width = 30;
                    cDel.Name = STR_COLUMN_DEL;
                    cDel.DataPropertyName = STR_COLUMN_DEL;
                    dgvOrderDetail.Columns.Add(cDel);
                }

                DataSet ds = new DataSet();

                if (handler.getProductById(ds, STR_TABLE_ADD_ORDER_DETAIL, ProId) == false)
                {
                    MessageBox.Show(ERR_LOAD_PRO_FAIL);
                    return;
                }

                ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Product quantity"] = 0;

                DataRow dr = dsData.Tables[STR_TABLE_ADD_ORDER_DETAIL].NewRow();
                dr["Product ID"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Product ID"];
                dr["Product quantity"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Product quantity"];
                dr["Name"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Name"];
                dr["Price"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Price"];
                dr["Detail"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Detail"];
                dr["Unit"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Unit"];
                dr["Tax"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Tax"];
                dr["Warranty"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Warranty"];
                dr["Discount type"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Discount type"];
                dr["Discount value"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Discount value"];
                dr["Discount Status"] = ds.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows[0]["Discount Status"];

                dsData.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows.Add(dr);

                dgvOrderDetail.DataSource = dsData;
                dgvOrderDetail.DataMember = STR_TABLE_ADD_ORDER_DETAIL;

                // lock datagridview order detail
                lockGridColumn();

                // Column Del
                dgvOrderDetail[STR_COLUMN_DEL, dgvOrderDetail.Rows.Count - 1].Value = Properties.Resources.cancel;
                dgvOrderDetail["Product quantity", dgvOrderDetail.Rows.Count - 1].ToolTipText = "Max = " + dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + ProId].Rows.Count;
            }
        }

        private void btnAddCustomer_Click(object sender, EventArgs e)
        {

        }

        private void calculateData()
        {
            if (dgvOrderDetail.Rows.Count > 0)
            {
                double sum = 0, tax = 0;

                for (int i = 0; i < dgvOrderDetail.Rows.Count; i++)
                {
                    if (dgvOrderDetail["Discount status", i].Value.ToString().Equals(STR_AVAILABE_STATUS))
                    {
                        if (dgvOrderDetail["Discount type", i].Value.ToString().Equals(STR_DISCOUNT_PERCENT))
                        {
                            sum += Convert.ToDouble(dgvOrderDetail["Price", i].Value.ToString()) *
                               Convert.ToDouble(dgvOrderDetail["Product quantity", i].Value.ToString()) * (100 - Convert.ToDouble(dgvOrderDetail["Discount value", i].Value.ToString())) / 100;

                            tax += Convert.ToDouble(dgvOrderDetail["Price", i].Value.ToString()) *
                                   Convert.ToDouble(dgvOrderDetail["Product quantity", i].Value.ToString()) * (100 - Convert.ToDouble(dgvOrderDetail["Discount value", i].Value.ToString())) / 100 * (100 + Convert.ToDouble(dgvOrderDetail["Tax", i].Value.ToString())) / 100;
                        }
                        else
                        {
                            sum += Convert.ToDouble(dgvOrderDetail["Price", i].Value.ToString()) *
                                   Convert.ToDouble(dgvOrderDetail["Product quantity", i].Value.ToString()) - Convert.ToDouble(dgvOrderDetail["Discount value", i].Value.ToString());

                            tax += (Convert.ToDouble(dgvOrderDetail["Price", i].Value.ToString()) *
                                   Convert.ToDouble(dgvOrderDetail["Product quantity", i].Value.ToString()) - Convert.ToDouble(dgvOrderDetail["Discount value", i].Value.ToString())) * (100 + Convert.ToDouble(dgvOrderDetail["Tax", i].Value.ToString())) / 100;
                        }
                    }
                    else
                    {
                        sum += Convert.ToDouble(dgvOrderDetail["Price", i].Value.ToString()) *
                               Convert.ToDouble(dgvOrderDetail["Product quantity", i].Value.ToString());

                        tax += Convert.ToDouble(dgvOrderDetail["Price", i].Value.ToString()) *
                               Convert.ToDouble(dgvOrderDetail["Product quantity", i].Value.ToString()) * (100 + Convert.ToDouble(dgvOrderDetail["Tax", i].Value.ToString())) / 100;
                    }
                }

                txtSum.Text = sum.ToString("C2");
                txtTax.Text = tax.ToString("C2");
            }
            else
            {
                txtSum.Text = "";
                txtTax.Text = "";
            }
        }

        private void dgvOrderDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (sMode.Equals(STR_MODE_ADD))
            {
                try
                {
                    int iQuantity = Convert.ToInt32(dgvOrderDetail["Product quantity", e.RowIndex].Value.ToString());
                }
                catch (Exception)
                {
                    MessageBox.Show(ERR_QUANTITY_VALIDATE + dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID +  dgvOrderDetail["Product ID", e.RowIndex].Value.ToString()].Rows.Count);
                    dgvOrderDetail["Product quantity", e.RowIndex].Value = 0;
                    return;
                }

                if (Convert.ToInt32(dgvOrderDetail["Product quantity", e.RowIndex].Value.ToString()) < 0 || Convert.ToInt32(dgvOrderDetail["Product quantity", e.RowIndex].Value.ToString()) > dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + dgvOrderDetail["Product ID", e.RowIndex].Value.ToString()].Rows.Count)
                {
                    MessageBox.Show(ERR_QUANTITY_VALIDATE + dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + dgvOrderDetail["Product ID", e.RowIndex].Value.ToString()].Rows.Count);
                    dgvOrderDetail["Product quantity", e.RowIndex].Value = 0;
                    return;
                }
            }

            calculateData();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(SMS_SAVE_ASK, "Delete", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            showButton(false);
            lockControl1(false);
            lockOrderDetail(true);

            if (sMode.Equals(STR_MODE_ADD))
            {
                OrderHandler handler = new OrderHandler();


                // --not finish
                // Add order
                if (handler.addOrder() == false)
                {
                    MessageBox.Show(ERR_ADD_ORDER_FAIL);
                    return;
                }

                // Add order detail
                for (int i = 0; i < dgvOrderDetail.Rows.Count; i++)
                {
                    //if (handler.addOrderDetailByID(Convert.ToInt32(dgvOrderDetail["Order ID", i].Value.ToString()), dgvOrderDetail["Product ID", i].Value.ToString(), Convert.ToInt32(dgvOrderDetail["Product quantity", i].Value.ToString())) == false)
                    //{
                    //    MessageBox.Show(ERR_ADD_ORDER_DETAIL_FAIL);
                    //    return;
                    //}
                    
                    int iQuantity = Convert.ToInt32(dgvOrderDetail["Product quantity", i].Value.ToString());
                    
                    // Update serial
                    for (int j = 1; j <= iQuantity; j++) 
                    {
                        //if (handler.updateSerial(dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + dgvOrderDetail["Product ID", i].Value.ToString()].Rows[j][0].ToString()))
                        //{
                        //    MessageBox.Show(ERR_UPDATE_SERIAL_FAIL);
                        //    return;
                        //}

                        //MessageBox.Show(dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + dgvOrderDetail["Product ID", i].Value.ToString()].Rows[j][0].ToString());
                    }
                }
                
                dsData.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows.Clear();
                dgvOrderDetail.Columns.Clear();
            }
            else
            {
                OrderHandler handler = new OrderHandler();

                // --not finish
                // Update order
                if (handler.updateOrder() == false)
                {
                    MessageBox.Show(ERR_UPDATE_ORDER_FAIL);
                    return;
                }

                // Update order detail
                for (int i = 0; i < dgvOrderDetail.Rows.Count; i++)
                {
                    if (handler.updateOrderDetailByID(Convert.ToInt32(dgvOrderDetail["Order ID", i].Value.ToString()), dgvOrderDetail["Product ID", i].Value.ToString(), Convert.ToInt32(dgvOrderDetail["Product quantity", i].Value.ToString())) == false)
                    {
                        MessageBox.Show(ERR_UPDATE_ORDER_FAIL);
                        return;
                    }
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            showButton(false);
            lockControl1(false);
            lockOrderDetail(true);

            // Delete table in dataset
            for (int i = 0; i < dgvOrderDetail.Rows.Count; i++)
            {
                dsData.Tables[STR_TABLE_SERIAL_BY_PRO_ID + dgvOrderDetail["Product ID", i].Value.ToString()].Rows.Clear();
            }

            if (dsData.Tables.Contains(STR_TABLE_ADD_ORDER_DETAIL))dsData.Tables[STR_TABLE_ADD_ORDER_DETAIL].Rows.Clear();
            dgvOrderDetail.Columns.Clear();
        }

        private void dgvOrderDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                try
                {
                    dgvOrderDetail.Rows.RemoveAt(e.RowIndex);
                }
                catch (Exception ex)
                {
                    // Ignore
                    //MessageBox.Show(ex.Message);
                }
            }
        }
    }
}
